package com.liangtian.mdm.material.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.material.model.WlLb;
import com.liangtian.mdm.material.model.WlbmJldw;
import com.liangtian.mdm.material.model.WlbmLbJldw;
import com.liangtian.mdm.material.service.WlLbService;
import com.liangtian.mdm.material.service.WlbmJldwService;
import com.liangtian.mdm.material.service.WlbmLbJldwService;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.system.user.util.ExcelImport;
import com.liangtian.mdm.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/wlbmLbJldwController")
public class WlbmLbJldwController extends BaseController {

    @Autowired
    private WlbmLbJldwService wlbmLbJldwService;

    // 日志服务接口对象
    @Autowired
    SysLogService sysLogServiceImpl;

    // Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    @Autowired
    JdbcDao jdbcDao;

    // private ExcelImport ExcelImport = new ExcelImport();

    @Autowired
    private WlLbService wlLbService;

    @Autowired
    private WlbmJldwService wlbmJldwService;

    private List<WlbmLbJldw> wlbmLbJldwListByExport = null;
    private Map<String, Object> wlbmLbJldwmap = null;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/getWlbmLbJldwByCond", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getWlbmLbJldwByCond(HttpServletRequest request, WlbmLbJldw lbjldw) {
        Map paramMap = RequestUtils.paramToMap(request, WlbmLbJldw.class, false);
        PageInfo pageInfo = wlbmLbJldwService.getWlbmLbJldwByCond(paramMap);
        List l = pageInfo.getList();
        wlbmLbJldwListByExport = pageInfo.getList();
        wlbmLbJldwmap = paramMap;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @RequestMapping(value = "/insertWlbmLbJldw", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertWlbmLbJldw(WlbmLbJldw lbjldw, HttpServletRequest request) {
        // 获取当前日期
        Date date = new Date();
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        int count = wlbmLbJldwService.insertWlbmLbJldw(lbjldw);
		/*// ==============================记录操作日志start===============================================
		SysLog sysLog = new SysLog();
		sysLog.setUserName(user.getUserName());
		sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
		sysLog.setOperationDate(date);
		if (count > 0) {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",新增物料类别计量单位成功");
		} else {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",新增物料类别计量单位失败");
		}
		sysLogServiceImpl.insertLog(sysLog);
		// ==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("新增物料类别计量单位[" + lbjldw.getLbbm() + "," + lbjldw.getFh() + "]",
                SysLogEnum.WLBM_LBJLDW.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    @ResponseBody
    @RequestMapping(value = "/checkWlbmLbJldwExist", method = RequestMethod.POST)
    public JSONObject checkWlbmLbJldwExist(WlbmLbJldw lbjldw) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = wlbmLbJldwService.checkWlbmLbJldwExist(lbjldw);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteWlbmLbJldwByIds", method = RequestMethod.POST)
    public ResultObject deleteWlbmLbJldwByIds(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids)) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("idList", ids.split(","));
        int ret = wlbmLbJldwService.deleteWlbmLbJldwByIds(map);
        int f = ret > 0 ? 1 : 0;
        SysLogUtil.insertLog("删除物料类别计量单位[" + ids + "]",
                SysLogEnum.WLBM_LBJLDW.getCode(), SysLogEnum.SC.getCode(), request);
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }
	
	/*@RequestMapping(value = "wlbmLbJldwExport", method = RequestMethod.GET)
    @ResponseBody
    public String wlbmLbJldwExport(HttpServletResponse response,HttpServletRequest request) {
    	String tablename=request.getParameter("tableName");
    	XSSFRow row = null;
		XSSFCell cell = null;
		
		// 声明一个工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet("类别计量单位");
		XSSFCellStyle style = workbook.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	    row = sheet.createRow(0);
	    sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));
	    cell=row.createCell(0);
	    cell.setCellValue("类别计量单位");
	    cell.setCellStyle(style);
	    
		Comment comment = null;
		CreationHelper factory = workbook.getCreationHelper();
		Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = factory.createClientAnchor();
       
		
		
        row = sheet.createRow(1);
		sheet.setColumnWidth(0, 30*220);  //设置第一列的宽度
		cell=row.createCell(0);
		cell.setCellValue("物料类别小类代码");
		comment = drawing.createCellComment(anchor);
		comment.setString(new XSSFRichTextString("小类代码不允许为空"));
		cell.setCellComment(comment);
		
		sheet.setColumnWidth(1, 30*200);  //设置第二列的宽度
		cell=row.createCell(1);
		cell.setCellValue("计量单位名称");
		comment = drawing.createCellComment(anchor);
		comment.setString(new XSSFRichTextString("计量单位名称不允许为空"));
		cell.setCellComment(comment);
		
		cell=row.createCell(2);
		cell.setCellValue("说明");

		outExcel(tablename,workbook,response);
		return null;
    }
	
	private void outExcel(String title, XSSFWorkbook workbook, HttpServletResponse response) {
		OutputStream out = null;
		try {
			String fileName = title.replace(" ", "") + ".xlsx";
			out = response.getOutputStream();
			response.reset();// 清空输出流
			fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
			response.setHeader("Content-disposition", "attachment; filename="
					+ fileName);// 设定输出文件头
			response.setContentType("application/msdownload");// 定义输出类型
			workbook.write(out);
		} catch (IOException e) {
			throw new RuntimeException("导出数据异常");
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				throw new RuntimeException("导出关闭异常");
			} // 关闭流
		}
	}*/

    /**
     * 导出模板
     */
    @RequestMapping(value = "wlbmLbJldwExport", method = RequestMethod.GET)
    @ResponseBody
    public String wlbmLbJldwExport(HttpServletResponse response, HttpServletRequest request) {
        String path = IoUtil.getTemplatePath();
        String fileName = TemplateName.WLBM_LBJLDW_TEMPLATE;//服务器上存的文件名
        String uploadFileName = "物料类别计量单位添加模板";//给用户下载看到的文件名
        ExportUtil.exportTemplate(path, fileName, uploadFileName, response);
		/*InputStream inStream = null;
		String fileName = null;
		OutputStream outStream = null;
		try {
			String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
			path=path.replace('/', '\\'); // 将/换成\ 
			path=path.replace("classes\\", ""); //去掉class\ 
			path=path.replace("file:\\", ""); //file:\ 
			path += "doc\\dataTemplate";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/vnd.ms-excel");
			fileName = "物料类别计量单位添加模板.xlsx";
			response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
			File file = new File(path,fileName);
			inStream = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int len;
			outStream = response.getOutputStream();
			while((len = inStream.read(bytes)) != -1 ) {
				outStream.write(bytes, 0, len);
	        }
			outStream.flush();
			outStream.close();
			outStream = null;
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(inStream != null){
				try{inStream.close();}
				catch(Exception e){}
			}
		}*/
        return null;
    }

    /**
     * 导入物料类别计量单位
     */
    @RequestMapping(value = "ExcelImport", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject ExcelImport(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        try {
            String tableName = request.getParameter("tableName");
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            SysLogUtil.insertLog("批量导入物料类别计量单位",
                    SysLogEnum.WLBM_LBJLDW.getCode(), SysLogEnum.PD.getCode(), request);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = ExcelImport.getWorkbook(uploadFile);
            int sheetNum = 0;
            // 得到sheet总数
            sheetNum = book.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = book.getSheetAt(i);
                List<Object[]> valueList = ExcelImport.read(sheet);
                // 插入数据
                if (valueList != null && valueList.size() > 0) {
                    result = checkImportList(valueList, tableName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * * <p>Title: 校验用户输入的数据</p>
     * <p>Company:@param valueList
     * <p>Company:@param tableName
     * <p>Company:@param conn
     * <p>Company:@return </p>
     */
    @RequestMapping(value = "/checkImportList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject checkImportList(List<Object[]> valueList, String tableName) {
        ExcelUtil eu = new ExcelUtil();
        String fileName = "";
        ResultObject resuObj = null;
        StringBuffer sb = new StringBuffer();//声明拼接符
        valueList.remove(0);
        if (0 != valueList.size() && null != valueList) {
            for (int j = 0; j < valueList.size(); j++) {//获取用户将导入的数据n条
                String[] row = (String[]) valueList.get(j);//获取行
                for (int k = 0; k < row.length; k++) {
                    String cell = row[k];//获取每固定行一列（0,0）
                    sb.append(check_column(j, k, cell, row));
                }

            }
        } else {
            sb.append("@@@@" + "请在模板中填写需要导入的数据！");
        }

        if (sb.toString().equals("")) {
            String[] headArray = {"USER_NAME", "USER_ACCOUNT", "USER_EMAIL", "USER_PHONE", "USER_TELEPHONE", "ORGANIZATION_ID"};
            List<String> sqls = genSql(tableName, valueList, headArray);
            boolean sucess = jdbcDao.executeSqlList(sqls, true);
            if (sucess) {
                resuObj = new ResultObject("true", "导入失成功!");
            }
        } else {
            fileName = "wllbjldwImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
            try {
                ExportUtil.errTxt(sb.toString(), fileName);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
			/*try {
				fileName="物料类别计量单位批量导入"+"@@@@"+new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+".txt";
				eu.errTxt(sb.toString(), fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}*/
            resuObj = new ResultObject("false", fileName);
        }
        return resuObj;
    }

    public String check_column(int row, int column, String cell, String[] coll) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        //校验每行数据的每一列，错误的拼接成string，正确的不拼接
        if (column == 0) {//说明是第一列（校验物料类别小类代码）
            if (cell.equals("") || cell == null || cell.equals(" ")) {//如果数据为空
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,物料类别小类代码为空！");
            } else {
                if (6 != cell.length()) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,物料类别小类代码填写错误,请输入6位小类物料代码！");
                } else {
                    WlLb wllb = new WlLb();
                    wllb.setLbbm(cell);
                    WlLb wlLb = wlLbService.getWlLbById(wllb);
                    if (null == wlLb) {
                        sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,物料类别小类代码不存在！");
                    }
                }
            }

        } else if (column == 1) {//说明是第二列（校验计量单位名称）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,计量单位名称为空！");
            } else {
                WlbmJldw dw = new WlbmJldw();
                dw.setJldw(cell);
                WlbmJldw jldw = wlbmJldwService.getWlbmJldwByIdOrName(dw);
                if (null == jldw) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,计量单位:" + "'" + cell + "'" + "不存在!");
                } else {
                    WlbmLbJldw lbjldw = new WlbmLbJldw();
                    lbjldw.setLbbm(coll[0]);
                    lbjldw.setMc(cell);
                    int count = wlbmLbJldwService.checkWlbmLbJldwExist(lbjldw);
                    if (0 < count) {
                        sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,该类别下已存在该计量单位！");
                    }
                }
            }
        }
        return sb.toString();

    }

    /*
     * @description:向数据库表中插入数据(1000行插入一次)
     * @param tableName,conn,sqlStr,subList,headArray
     * @return
     * @time:2016年9月07日
     */
    public List<String> genSql(String tableName, List<Object[]> subList, String[] headArray) {
        List<String> sqls = new ArrayList<String>();
        // 获取值集合
        for (int j = 0; j < subList.size(); j++) {
            StringBuffer sb = new StringBuffer("");
            sb.append(" insert into " + tableName + " (LBJLDW_ID,")
                    .append("LBBM_ID,LBBM,MC,SM,JLDW_ID,FH)")
                    .append(" VALUES( WLBM_LBJLDW_seq.nextval,");

            String[] row = (String[]) subList.get(j);
            WlLb wllb = new WlLb();
            wllb.setLbbm(row[0]);
            WlLb wlLb = wlLbService.getWlLbById(wllb);
            if (null != wlLb) {
                sb.append("'").append(wlLb.getLbbmId()).append("',");
            }
            sb.append("'").append(row[0]).append("',").append("'").append(row[1]).append("',")
                    .append("'").append(row[2].trim()).append("',");
            WlbmJldw jldw = new WlbmJldw();
            jldw.setJldw(row[1]);
            WlbmJldw dw = wlbmJldwService.getWlbmJldwByIdOrName(jldw);
            if (null != dw) {
                sb.append("'").append(dw.getJldwId()).append("',").append("'").append(dw.getFh()).append("')");
            }

            sqls.add(sb.toString());
            System.out.print(sb.toString());
        }
        return sqls;
    }

    /*
     * 2017-06-29
     * jyh
     * 错误日志下载抽取至LogErrorsController中
     */

    /**
     * * <p>Title: 导入数据，错误文档</p>
     * <p>Company:@param response
     * <p>Company:@param request </p>
     */
    /*@RequestMapping(value = "downLoadErr", method = RequestMethod.POST)
    @ResponseBody
    public void downLoadErr(HttpServletResponse response,HttpServletRequest request){
    	String fileName = request.getParameter("err_fileName");
		String path = WlbmLbJldwController.class.getProtectionDomain().getCodeSource()  
                .getLocation().getPath();
		String file=path.substring(1, path.indexOf("/WEB-INF/classes"))+"/error_text/"+fileName;
		System.out.println("file:"+file);
		try {
			InputStream inStream = new FileInputStream(file);
			if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
			     fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
			}else{
			     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
			}
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.addHeader("Content-Disposition",  "attachment;filename=\"" + fileName + "\"");
			// 循环取出流中的数据
			byte[] b = new byte[100];
			int len;
			OutputStream output=response.getOutputStream();
			while ((len = inStream.read(b)) > 0)
				output.write(b, 0, len);
			
			output.flush();
			output.close();
			inStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
    @ResponseBody
    @RequestMapping(value = "/getDelCountByJldwId", method = RequestMethod.POST)
    public JSONObject getDelCountByJldwId(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            String jldwId = request.getParameter("jldwId");
            Map<String, Object> map = new HashMap<>();
            map.put("jldw_id", jldwId);
            int count = this.wlbmLbJldwService.getDelCountByJldwId(map);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getJldw", method = RequestMethod.POST)
    public JSONObject getJldw(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String lbbm = request.getParameter("lbbm");
        Map<String, Object> cond = new HashMap<>();
        cond.put("lbbm", lbbm);
        List<WlbmLbJldw> list = wlbmLbJldwService.getWlbmLbJldwByCond2(cond);
        jsonObject.put("list", list);
        return jsonObject;
    }

    /**
     * 导出当前页数据
     *
     * @param request
     * @return
     
     * @date 2018-02-02
     */
    @RequestMapping(value = "WlbmLbJldwExportExcel", method = RequestMethod.POST)
    @ResponseBody
    public String WlbmLbJldwExportExcel(HttpServletResponse response, HttpServletRequest request) {
        if (wlbmLbJldwListByExport.size() > 0 && wlbmLbJldwListByExport != null) {
            wlbmLbJldwService.exportWlbmLbJldw(wlbmLbJldwListByExport, response);
        }
        return null;
    }

    /**
     * 导出所有数据
     *
     */
    @RequestMapping(value = "WlbmLbJldwExportExcel2", method = RequestMethod.POST)
    @ResponseBody
    public String WlbmLbJldwExportExcel2(HttpServletResponse response, HttpServletRequest request) {
        String start = request.getParameter("Second_PageHelper");
        String end = request.getParameter("First_PageHelper");
        if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
            wlbmLbJldwmap.put("pageNum", start);
            wlbmLbJldwmap.put("limit", end);
            PageInfo pageInfo = wlbmLbJldwService.getWlbmLbJldwByCond3(wlbmLbJldwmap);
            List l = pageInfo.getList();
            if (l.size() > 0 && l != null) {
                wlbmLbJldwService.exportWlbmLbJldw(l, response);
            }
        }
        return null;
    }

}
